import axios from "axios";
import appStore from "../store/AppStore";
import DeviceInfo from "react-native-device-info";
import { userStore } from "../store";
import { uploadError } from "../utils/util";
import backgroundTimePlugin from "../plugins/backgroundTimer";


axios.defaults.timeout = 20000;
axios.defaults.maxContentLength = 1048576;
axios.defaults.headers["Accept"] = "application/json, text/plain, */*";
axios.defaults.headers["Content-Type"] = "application/json";
/* 添加拦截器 */
/*
  判断全局变量是否存在,不存在则从storage取
*/
// axios.defaults.baseURL = API
axios.interceptors.request.use(async function(config) {
  if (config.outSite !== "login") {
    if (!IsNullOrEmpty(global.token)) {
      config.headers["token"] = global.token || "";
    }

    config.headers["source"] = Platform.OS;
    config.headers["version"] = DeviceInfo.getVersion();
    if (!config.data) {
      config.data = {};
    }
  }


  if (config.data) {
    if (config.data.showLoading) {
      const showLoading = appStore.showLoading;
      if (!showLoading) {
        appStore.startFetch();
      }
    }
    delete config.data.showLoading;
    //签名
    // config.data.sig=getSign(config.data)
    // config.data = queryString.stringify(config.data);
  }
  if (config.headers) {
    if (config.headers.showLoading) {
      const showLoading = appStore.showLoading;
      if (!showLoading) {
        appStore.startFetch();
      }
    }

    delete config.headers.showLoading;
  }
  if (!IsNullOrEmpty(config.showLoading)) {

    if (config.showLoading) {
      const showLoading = appStore.showLoading;
      if (!showLoading) {
        logger("拦截请求", "显示加载框");
        appStore.startFetch();
      }
    }

    delete config.showLoading;
  }

  //这个很重要，对于IOS，如果是get请求，必须删除data
  if (config.method === "get") {
    if (config.params && !IsNullOrEmpty(config.params.showLoading)) {
      if (config.params.showLoading == true) {
        const showLoading = appStore.showLoading;
        if (!showLoading) {
          logger("拦截请求", "显示加载框");
          appStore.startFetch();
        }
      }
      delete config.params.showLoading;
    }


    delete config.data;
    // if(config.params)
    // {
    //     config.params.sig=getSign(config.params)
    // }
    // else{
    //     config['params']={};
    //     config.params['sig']=getSign(null)
    // }
  }

  logger("拦截请求", config.url, config.data, config.params);
  // logger('拦截请求参数', config);

  return config;
}, function(error) {
  return Promise.reject(error);
});

// 防抖
const debounceTokenCancel = new Map();
axios.interceptors.request.use(config => {
  const { url, params, data, isDebounce } = config
  if (isDebounce) {
    const tokenKey = `${url}-${params ? JSON.stringify(params) : ''}-${data ? JSON.stringify(data) : ''}`
    const cancel = debounceTokenCancel.get(tokenKey)
    if (cancel) {
      cancel()
    }
    return new Promise((resolve, reject) => {
      backgroundTimePlugin.setTimer({
        key: `axios-${tokenKey}`,
        type: 'timeout',
        time: 200,
        callback: () => {
          backgroundTimePlugin.remove({key: `axios-${tokenKey}`, type: 'timeout'})
          debounceTokenCancel.delete(tokenKey)
          resolve(config)
        }
      })

      debounceTokenCancel.set(tokenKey, () => {
        backgroundTimePlugin.remove({key: `axios-${tokenKey}`, type: 'timeout'})
        debounceTokenCancel.delete(tokenKey)
        reject(new Error('操作过于频繁'))
      })
    })
  } else {
    return config
  }
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(function(response) {
  const { config, data } = response;
  // logger("拦截响应", data)
  appStore.finishFetch();

  if (IsNullOrEmpty(data.code) || data.code == 200) {
    return Promise.resolve(data);
  } else {
    logger("请求非200", config.url, data);
    // Toast.show(`请求错误【url：${config.url}】`)
  }
  if (data.code == 50000 || data.code == 403) {
    userStore.clearInfoAndJumpToLogin();
  }
  // if (config) {
  //   uploadError(`接口调用失败：${config.url}`, `请求参数：${config.data}，返回内容：${JSON.stringify(data)}`);
  // }
  // let formatData=Object.assign(data,{msg:data.statusText});
  // logger('格式化错误',formatData)
  return Promise.reject(data);

}, async function(err) {
  logger("响应失败", JSON.stringify(err));
  appStore.finishFetch();
  // if (err.response.status === 429) {
  //   return Promise.reject({ message: "网络请求频繁,请稍后再试" })
  // }
  if (err.response && err.response.data) {
    // 请求已发出，但服务器响应的状态码不在 2xx 范围内
    const { data,config } = err.response;
    logger("响应失败", data.status);
    // if(config)
    // {
    //   uploadError(`接口调用失败：${config.url}`,`请求参数：${config.data||JSON.stringify(config.params)}，返回内容：${JSON.stringify(data)}`)
    // }
    let formatData = Object.assign(data, { message: data.message });
    return Promise.reject(formatData);
  } else {
    const errorObj = { msg: err.msg || "网络请求错误" };
    return Promise.reject(errorObj);
  }
});
export default axios;
